const toStr = Object.prototype.toString;

export const percentLimitColors = [
	{ color: '#f56c6c', percentage: 20 },
	{ color: '#e6a23c', percentage: 40 },
	{ color: '#6f7ad3', percentage: 60 },
	{ color: '#1989fa', percentage: 80 },
	{ color: '#5cb87a', percentage: 100 }
];

export function getPercentage(numerator, denominator, scale=2){
	if(!denominator) return 0;
	return +(parseFloat(accMul(accDiv(numerator || 0, denominator), 100)).toFixed(scale));
}

export function isUndef(v) {
  return v === undefined || v === null;
}

export function isDef(v) {
  return v !== undefined && v !== null;
}

export function isTrue(v) {
  return v === true;
}

export function isFalse(v) {
  return v === false;
}

// 检测对象类型
export function isRegExp(v) {
  return toStr.call(v) === '[object RegExp]';
}
export function isArray(v) {
  return toStr.call(v) === '[object Array]';
}
export function isString(v) {
  return toStr.call(v) === '[object String]';
}
export function isObject(v) {
  return toStr.call(v) === '[object Object]';
}
export function isFunction(v) {
  return toStr.call(v) === '[object Function]';
}
export function isNumber(v) {
  return toStr.call(v) === '[object Number]';
}
export function isDate(v) {
  return toStr.call(v) === '[object Date]';
}

// 删除数组中某一个
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item);
    if (index > -1) {
      return arr.splice(index, 1);
    }
  }
  return arr;
}
export function matches(pattern, name) {
  if (Array.isArray(pattern)) {
    return pattern.indexOf(name) > -1;
  } else if (typeof pattern === 'string') {
    return pattern.split(',').indexOf(name) > -1;
  } else if (isRegExp(pattern)) {
    return pattern.test(name);
  }
  return false;
}
/**
 * todo
 */
export function isapp() {
  if (process.env.NODE_ENV === 'production') {
    // return navigator.userAgent.toLowerCase().indexOf(projectTag) >= 0;
    return navigator.userAgent.toLowerCase().indexOf('micromessenger') < 0;
  }
  return false;
}
export function moneyFilter(text) {
  if (text.indexOf('.') >= 0) {
    return text.split('.')[0] - 0;
  }
  return text - 0;
}

export function isIPhoneX() {
  // iPhone X、iPhone XS
  return /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 3 && window.screen.width === 375 && window.screen.height === 812;
}
export function isIPhoneXSMax() {
  // iPhone XS Max
  return /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 3 && window.screen.width === 414 && window.screen.height === 896;
}
export function isIPhoneXR() {
  // iPhone XR
  return /iphone/gi.test(window.navigator.userAgent) && window.devicePixelRatio && window.devicePixelRatio === 2 && window.screen.width === 414 && window.screen.height === 896;
}
export function IPhoneX() {
  return isIPhoneX() || isIPhoneXSMax() || isIPhoneXR();
}

export function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

export function accDiv(arg1, arg2) {
	var arg1 = arg1 || 0,
	arg2 =arg2 || 0;
  var t1 = 0,
    t2 = 0,
    r1, r2;
  try {
    t1 = arg1.toString().split(".")[1].length
  } catch (e) {}
  try {
    t2 = arg2.toString().split(".")[1].length
  } catch (e) {}
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}

export function accMul(arg1, arg2) {
	var arg1 = arg1 || 0,
	arg2 =arg2 || 0;
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length
  } catch (e) {}
  try {
    m += s2.split(".")[1].length
  } catch (e) {}
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

export function accAdd(arg1, arg2) {
	var arg1 = arg1 || 0,
	arg2 =arg2 || 0;
  var r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (Math.round(arg1 * m) + Math.round(arg2 * m)) / m;
}

export function accSub(arg1, arg2) {
	var arg1 = arg1 || 0,
	arg2 =arg2 || 0;
  var r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (Math.round(arg1 * m) - Math.round(arg2 * m)) / m;
}

export function formatNumByThousand(number) {
	let digit = ''
	let numbers = number.toString().split('').reverse()
	const flag = number.toString().indexOf('.') > -1;
	if(flag){
		digit = number.toString().split('.')[1]
		numbers = number.toString().split('.')[0].split('').reverse()
	}
	const segs = []

	while (numbers.length) segs.push(numbers.splice(0, 3).join(''))

	return segs.join(',').split('').reverse().join('') + (flag?'.':'') + digit
}

export function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 时间格式化
export function formatDateByFmt(date, fmt) {
  var date = new Date(date);
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      var str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
    }
  }
  return fmt;
}

export function formatDate(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}

export function formatDateTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
/**
 * 获取开始时间和结束时间，格式：yyyy-MM-dd
 * 
 * @param {*} dateStr 时间字符串，格式：yyyy-MM-dd
 * @param {*} dateType 时间类型，【year,month,day】目前支持month
 * @param {*} dateVal 差值，正负整数
 */
export function getTimeSlot(dateStr, dateType, dateVal){
  var date1 = new Date()
  if (dateStr) {
    // 转换文本的日期格式
    dateStr = dateStr.replace(/-/g, '/'); // 转为格式"2015/05/26";
    // 创建日期对象，并初始化，完成文本转日期
    date1 = new Date(dateStr)
  }

  var year = date1.getFullYear(), // 年
    month = date1.getMonth() + 1, // 月
    day = date1.getDate(), // 日
    days = new Date(year, month, 0)
  days = days.getDate(); // 获取当前日期中月的天数

  if (dateType === 'year') {
    return null
  } else if (dateType === 'month') {
    var year2 = year,
      month2 = parseInt(month) + parseInt(dateVal),
      day2 = day
    if (dateVal > 0) {
      if (month2 > 12) {
        year2 = parseInt(year2) + parseInt((parseInt(month2) / 12 == 0 ? 1 : parseInt(month2) / 12));
        month2 = parseInt(month2) % 12;
      }
    } else {
      if (month2 <= 0) {
        var absM = Math.abs(month2);
        year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
        month2 = 12 - (absM % 12);
      }
    }
    var days2 = new Date(year2, month2, 0)
    days2 = days2.getDate()
    if (day2 > days2) {
      day2 = days2;
    }

    if (dateVal > 0) {
      return {
        startDate: [year, month, day].map(formatNumber).join('-'),
        endDate: [year2, month2, day2].map(formatNumber).join('-')
      }
    } else {
      return {
        startDate: [year2, month2, day2].map(formatNumber).join('-'),
        endDate: [year, month, day].map(formatNumber).join('-')
      }
    }
  } else if (dateType === 'day') {
    return null
  }
}

/**
 * 获取两个日期之间的天数 开始日期的那天不算
 * @param dateString1 开始时间 yyyy-MM-dd
 * @param dateString2 结束时间 yyyy-MM-dd
 * @returns {number} 天数
 */
export function getDaysBetween(dateString1, dateString2) {
  var startDate = Date.parse(dateString1)
  var endDate = Date.parse(dateString2)
  var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
  return days
}

export function getLatlngCenter(itemList){
	let min_lat = 53
	let max_lat = 0
	let min_lng = 135
	let max_lng = 0
	itemList.forEach(item => {
		if (min_lat > item.lat) min_lat = item.lat
		if (min_lng > item.lng) min_lng = item.lng
		if (max_lat < item.lat) max_lat = item.lat
		if (max_lng < item.lng) max_lng = item.lng
	})
	return {
		lat: accDiv(accAdd(min_lat, max_lat), 2), 
		lng: accDiv(accAdd(min_lng, max_lng), 2)
	}
}

export function getAdcodeListByAdcode(adcode){
	const p = ('' + adcode).substring(0, 2)
	if ('' + p === '11' || '' + p === '12' || '' + p === '31' || '' + p === '50' || '' + p === '81' || '' +
		p === '82') {
		// 直辖市和港澳时，只有一级
		return [('' + adcode).substring(0, 2) + '0000']
	} else {
		return [('' + adcode).substring(0, 2) + '0000', ('' + adcode).substring(0, 4) + '00']
	}
}

/**
 * 获取两个字面量数组中比偶叫
 * @param {Object} arr1 左数组
 * @param {Object} arr2 右数组
 */
export function compareArrayToGetDiffs(arr1, arr2){
	let result = {
		same:[], // 相同的部分
		all:[], // 所有不同部分
		over1:[], // 左多的部分
		over2:[], // 右多的部分
		less1:[], // 左少的部分
		less2:[], // 右少的部分
	}
	if(arr1 && isArray(arr1) && arr2 && isArray(arr2)){
		if(arr1.length == 0) result = arr2;
		if(arr2.length == 0) result = arr1;
		let set1 = new Set();
		let set2 = new Set();
		arr1.forEach(x => set1.add(x));
		arr2.forEach(x => set2.add(x));
		let toDel1 = new Set();
		let toDel2 = new Set();
		set1.forEach(i => {
			if(set2.has(i)) toDel1.add(i)
		})
		set2.forEach(i => {
			if(set1.has(i)) toDel2.add(i)
		})
		let toDel = [...toDel1,...toDel2]
		toDel.forEach(i => {
			set1.delete(i)
			set2.delete(i)
		})
		result = {
			same: [...new Set(toDel)],
			all:[...set1,...set2], // 所有不同部分
			over1:[...set1], // 左多的部分
			over2:[...set2], // 右多的部分
			less1:[...set2], // 左少的部分
			less2:[...set1], // 右少的部分
		}
	}
	return result;
}

//对象转map
export function obj2Map(obj, userIntKey=false){
	  let map = new Map();
	  for(let key in obj) {
		   if(!userIntKey) map.set(''+key,obj[key]);
		   else map.set(parseInt(key),obj[key]);
	  }
	  return map;
}
 
 
//map转为json
export function map2Obj(map){
	 let obj = {};
	 for(let [k,v] of map) {
		 obj[k] = v;
	 }
	 return obj;
}

//当月第一天
export function getFirstDayOfMonth() {
  var today = new Date();
  var year = today.getFullYear();
  var month = today.getMonth() + 1; // 月份从 0 开始计数，所以需要加 1
  var formattedMonth = month < 10 ? '0' + month : month;
  var firstDay = year + '-' + formattedMonth + '-01';
  
  return firstDay;
}